import { toValue } from "vue"
import useEventListener from "./useEventListener"

const getDistance = (v1, v2) => {
    return Math.hypot(v2.x - v1.x, v2.y - v1.y)
}
const useLongTap = (ele, callback, options = {}) => {
    const { time = 500, offset = 5 } = options
    const element = toValue(ele)
    let timeout = null

    const initOffset = { x: 0, y: 0 }

    let stopMove = () => void 0
    const stop = () => {
        stopMove()
        clearTimeout(timeout)
        timeout = null
        stopStart()
        stopEnd()
    }

    const stopStart = useEventListener(ele, 'touchstart', (e) => {
        element.classList.add("forbid-select")
        timeout = setTimeout(() => {
            e.preventDefault()
            e.stopPropagation()
            callback(e)
        }, time)
        initOffset.x = e.touches[0].clientX
        initOffset.y = e.touches[0].clientY

        stopMove = useEventListener(element, "touchmove", (ev) => {
            const distance = getDistance(initOffset, {
                x: ev.touches[0].clientX,
                y: ev.touches[0].clientY
            })
            if (distance > offset) {
                clearTimeout(timeout)
                stopMove()
            }
        })
    }, { passive: false })

    const stopEnd = useEventListener(ele, 'touchend', () => {
        clearTimeout(timeout)
        stopMove()
        element.classList.remove("forbid-select")
    })

    return stop
}

export default useLongTap